package com.ztgf.shopping.service.shop;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.*;
import com.qiyuesuo.sdk.v2.exception.ServiceException;
import com.qiyuesuo.sdk.v2.http.*;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.request.*;
import com.qiyuesuo.sdk.v2.response.*;
import com.qiyuesuo.sdk.v2.utils.CryptUtils;
import com.qiyuesuo.sdk.v2.utils.MD5;
import com.qiyuesuo.sdk.v2.utils.StringUtils;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.file.models.service.IFileService;
import com.ztgf.order.models.bo.CorpAuthDetail;
import com.ztgf.order.models.dto.OrderContractEnclosureDTO;
import com.ztgf.order.models.dto.OrderContractParamRelationDTO;
import com.ztgf.order.models.dto.OrderContractRelationDTO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopQiyuesuoInfoMapper;
import com.ztgf.shopping.models.bo.shop.*;
import com.ztgf.shopping.models.bo.template.ContractStatusCallBackBO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopQiyuesuoInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopQiyuesuoInfoLogDTO;
import com.ztgf.shopping.models.dto.shop.ShopQualificationDTO;
import com.ztgf.shopping.models.service.shop.IShopQiyuesuoInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import com.ztgf.shopping.service.template.ContractTempletServiceImpl;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.bo.SmsInfoSaveCaptchaBO;
import com.ztgf.sms.models.dto.sms.SmsInfoDTO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.user.models.dto.UserLoginDTO;
import com.ztgf.user.models.service.IUserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.ztgf.common.utils.UtilConstants.isNull;

/**
 * 契约锁店铺信息控制器
 *
 * @author YUE
 * @Date 2020-06-15 16:18:38
 */
@Slf4j
@DubboService
public class ShopQiyuesuoInfoServiceImpl extends ServiceImpl<ShopQiyuesuoInfoMapper, ShopQiyuesuoInfoDTO> implements IShopQiyuesuoInfoService {

    // 初始化sdkClient
    @Value("${shop.qiyuesuo.service.sdkUrl}")
    private String serverUrl;

    @Value("${shop.qiyuesuo.service.appToken}")
    private String accessKey;

    @Value("${shop.qiyuesuo.service.appSecret}")
    private String accessSecret;

    @Value("${shop.qiyuesuo.order.secretKey}")
    private String secretKey;

    @Value("${shop.qiyuesuo.order.businessId}")
    private String orderBusinessId;

    @Value("${page.show.url}")
    private String pageShowUrl;

    @Value("${page.interface.url}")
    private String pageInterfaceUrl;

    @Value("${page.image.url}")
    private String pageImageUrl;

    @Value("${shop.qiyuesuo.service.signNumber}")
    private String createUser;
    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ShopQiyuesuoInfoMapper shopQiyuesuoInfoMapper;
    @Autowired
    private ContractTempletServiceImpl contractTempletService;
    @DubboReference
    private IOrderContractRelationService orderContractRelationService;
    @DubboReference
    private IOrderInfoService orderInfoService;
    @Autowired
    @Lazy
    private ShopInfoServiceImpl shopInfoService;
    @Autowired
    private ShopQualificationServiceImpl shopQualificationService;
    @DubboReference
    private IOrderContractParamRelationService orderContractParamRelationService;
    @Autowired
    private ShopQiyuesuoInfoLogServiceImpl shopQiyuesuoInfoLogService;
    @DubboReference
    private IOrderStatusService orderStatusService;
    @DubboReference
    private IFileService fileService;
    @DubboReference
    private IOrderContractEnclosureService orderContractEnclosureService;
    @DubboReference
    private ISmsInfoService smsInfoService;
    @DubboReference
    private IUserLoginService userLoginService;

    /**
     * 获取所有契约锁企业申请中的信息
     *
     * @return
     */
    @Override
    public List<ShopQiyuesuoInfoDTO> getListAuthenticationing() {
        Wrapper<ShopQiyuesuoInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("authentication_status", 4);//认证中
        return selectList(wrapper);
    }

    /**
     * 获取企业认证状态信息
     *
     * @param shopId
     * @return
     */
    @Override
    public ShopQiyuesuoAuthStateInfoBO getByQiyuesuoState(Long shopId) {
        ShopQiyuesuoAuthStateInfoBO shopQiyuesuoAuthStateInfoBO = new ShopQiyuesuoAuthStateInfoBO();
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = getByShopId(shopId);
        if (null == shopQiyuesuoInfoDTO) {
            shopQiyuesuoAuthStateInfoBO.setAuthState(false);
            shopQiyuesuoAuthStateInfoBO.setResult("没有此店铺信息");
            return shopQiyuesuoAuthStateInfoBO;
        }
        if (shopQiyuesuoInfoDTO.getAuthenticationStatus().equals("2")) {//认证 通过
            shopQiyuesuoAuthStateInfoBO.setAuthState(true);
            return shopQiyuesuoAuthStateInfoBO;
        }
        Result result = null;
        try {
            result = getEnterpriseAuthenticationStr(shopQiyuesuoInfoDTO);
        } catch (Exception e) {
            e.printStackTrace();
            shopQiyuesuoAuthStateInfoBO.setAuthState(false);
            shopQiyuesuoAuthStateInfoBO.setResult(CodeEnum.QIYUESUO_FAIL.getMsg());
            log.error("getEnterpriseAuthenticationStr is error", e);
            return shopQiyuesuoAuthStateInfoBO;
        }
        if (result.getCode() == CodeEnum.QIYUESUO_FAIL.getCode()) {
            shopQiyuesuoAuthStateInfoBO.setAuthState(false);
            shopQiyuesuoAuthStateInfoBO.setResult(result.getMsg());
            return shopQiyuesuoAuthStateInfoBO;
        }
        if (result.getCode() == CodeEnum.QIYUESUO_COMPANYAUTH_SAME_SUCCESS.getCode()) {
            shopQiyuesuoAuthStateInfoBO.setAuthState(true);
            shopQiyuesuoAuthStateInfoBO.setResult(result.getMsg());
            return shopQiyuesuoAuthStateInfoBO;
        }
        if (result.getCode() == CodeEnum.QIYUESUO_COMPANYAUTH_SAME.getCode()) {
            shopQiyuesuoAuthStateInfoBO.setAuthState(false);
            shopQiyuesuoAuthStateInfoBO.setResult(result.getMsg());
            return shopQiyuesuoAuthStateInfoBO;
        }
        shopQiyuesuoAuthStateInfoBO.setAuthState(false);
        shopQiyuesuoAuthStateInfoBO.setAuthUrl(result.getMsg());
        return shopQiyuesuoAuthStateInfoBO;
    }

    @Override
    public boolean add(ShopQiyuesuoInfoSaveBO saveBO) {
        ShopQiyuesuoInfoDTO dto = new ShopQiyuesuoInfoDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 需要签订合同的商家id
     *
     * @param jiaShopId
     * @param yiShopId
     */
    @Override
    public String promoteContract(Long jiaShopId, Long yiShopId, Long orderId, String param, byte[] bytes, String affix) {
        String contractDraftUrl;
        try {
            contractDraftUrl = this.createContractDraft(orderId, param, bytes, jiaShopId, yiShopId, affix);
        } catch (Exception e) {
            String errorLog = "订单id:" + orderId + " 合同创建失败";
            log.error(errorLog);
            log.error(e.getMessage());
            throw new RuntimeException(errorLog);
        }
        return contractDraftUrl;
    }

    /**
     * 根据店铺id获取契约锁信息
     *
     * @param shopId
     * @return
     */
    public ShopQiyuesuoInfoDTO getByShopId(Long shopId) {
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = new ShopQiyuesuoInfoDTO();
        //addMutInfo(shopQiyuesuoInfoDTO);
        shopQiyuesuoInfoDTO.setShopId(shopId);
//        Wrapper wrapper = new EntityWrapper();
//        wrapper.eq("shop_id",shopId);
//        return selectOne(wrapper);
        return shopQiyuesuoInfoMapper.selectOne(shopQiyuesuoInfoDTO);
    }

    /**
     * 根据店铺id获取契约锁信息
     *
     * @param shopId
     * @return
     */
    @Override
    public boolean getPassStatusByShopId(Long shopId) {
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = new ShopQiyuesuoInfoDTO();
        shopQiyuesuoInfoDTO.setShopId(shopId);
        return shopQiyuesuoInfoMapper.selectOne(shopQiyuesuoInfoDTO).getAuthenticationStatus().equals("2");
    }

    /**
     * 根据公司名字获取契约锁信息
     *
     * @param companyName
     * @return
     */
    @Override
    public ShopQiyuesuoInfoDTO getByCompanyName(String companyName) {
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = new ShopQiyuesuoInfoDTO();
        //addMutInfo(shopQiyuesuoInfoDTO);
        shopQiyuesuoInfoDTO.setCompanyName(companyName);
        return shopQiyuesuoInfoMapper.selectOne(shopQiyuesuoInfoDTO);
    }

    /**
     * 通过企业认证回调 更新状态
     *
     * @param shopQiyuesuoAuthCallBackInfoBO
     * @return
     */
    @Override
    public boolean updateByCallBackInfo(ShopQiyuesuoAuthCallBackInfoBO shopQiyuesuoAuthCallBackInfoBO) {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setInfoType(1);
        shopQiyuesuoInfoLogSaveBO.setType(1);
        shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(shopQiyuesuoAuthCallBackInfoBO));
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);

        String authInfo = shopQiyuesuoAuthCallBackInfoBO.getAuthInfo();
        CorpAuthDetail corpAuthDetail = JSON.parseObject(authInfo, CorpAuthDetail.class);
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = getByCompanyName(corpAuthDetail.getName());
        log.info(corpAuthDetail.getName() + ":企业验证回调了");
        if (null == shopQiyuesuoInfoDTO) {
            return false;
        }
        if (shopQiyuesuoAuthCallBackInfoBO.getStatus() != 1) {//认证不成功
            return false;
        }
        shopQiyuesuoInfoDTO.setAuthenticationStatus("2");
        shopQiyuesuoInfoDTO.setRegisterNo(corpAuthDetail.getRegisterNo());
        shopQiyuesuoInfoDTO.setLegalPerson(corpAuthDetail.getLegalPerson());
        return updateById(shopQiyuesuoInfoDTO);
    }

    /**
     * 根据回调内容签署合同
     *
     * @param signature
     * @param timestamp 时间搓
     * @param content   加密内容
     * @return
     * @throws Exception
     */
    @Override
    public String updateContactByCallBackInfo(String signature, String timestamp, String content) throws Exception {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setInfoType(1);
        shopQiyuesuoInfoLogSaveBO.setType(2);
        shopQiyuesuoInfoLogSaveBO.setResponseParam("加密内容：" + content + "--时间搓：" + content + "--signature" + signature);
        MD5 md5 = new MD5(timestamp + secretKey);
        String encryptMessage = md5.compute();
        String decrypt = null;
        if (encryptMessage.equals(signature)) {//解密相同
            decrypt = CryptUtils.aesDerypt(content, secretKey);
        }
        shopQiyuesuoInfoLogSaveBO.setRequetsParam(decrypt);
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
        ContractStatusCallBackBO contractStatusCallBackBO = JSON.parseObject(decrypt, ContractStatusCallBackBO.class);
        if (null == contractStatusCallBackBO) {
            log.error("契约锁没有信息!");
            return "success";
        }

        log.error("contractStatusCallBackBO--------------------"+JSON.toJSONString(contractStatusCallBackBO));
        String tenantName = contractStatusCallBackBO.getTenantName();
        if (StrUtils.isNotEmpty(tenantName)) {
            OrderInfoDTO orderInfoDTO = orderContractRelationService.getOrderInfoByContractId(Long.parseLong(contractStatusCallBackBO.getContractId()));
            if (null == orderInfoDTO) {
                log.error("此合同id不对应，请检查是否重新发起过合同");
                return "success";
            }
            log.error("合同签署成功回调--------------------1" + orderInfoDTO.getOrderNo());
            Long orderId = orderInfoDTO.getId();
            ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = getByName(tenantName);
            if (null == shopQiyuesuoInfoDTO) {
                log.error("本地无契约锁信息！!");
                return "success";
            }
            int signType = 0;
            if (Objects.equals(shopQiyuesuoInfoDTO.getShopId(), orderInfoDTO.getBuyShopId())) {//买家
                signType = OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode();
            }
            if (Objects.equals(shopQiyuesuoInfoDTO.getShopId(), orderInfoDTO.getSellShopId())) {//卖家
                signType = OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode();
            }
            log.error("合同签署成功回调--------------------2" + orderInfoDTO.getOrderNo());
            if (Objects.equals(contractStatusCallBackBO.getContractStatus(), "INVALIDING") ||
                    Objects.equals(contractStatusCallBackBO.getContractStatus(), "INVALIDED")) {//废弃合同回调
                log.info(contractStatusCallBackBO.getCallbackType() + "----- 签署方类型");

                orderStatusService.signAbandonContact(orderId, signType);//废弃合同
                return "success";
            }
            log.error("合同签署成功回调--------------------3" + orderInfoDTO.getOrderNo());
            OrderContractRelationDTO orderContractRelationDTO = orderContractRelationService.getByOrderId(orderId);
            if (!Objects.equals(orderContractRelationDTO.getContractId(), contractStatusCallBackBO.getContractId())) {
                log.info("此合同id不对应，请检查是否重新发起过合同");
                return "success";
            }
            log.error("交易合同签订开始----start--------------------"+JSON.toJSONString(orderInfoDTO));
            orderInfoService.signOver(orderId, signType);//交易合同
//            if(contractStatusCallBackBO.getContractStatus().equals("SIGNING")){//买家
//                orderInfoService.signOver(orderInfoDTO.getId(), OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode());
//            }
//
//            if(contractStatusCallBackBO.getContractStatus().equals("COMPLETE")){//卖家
//                orderInfoService.signOver(orderInfoDTO.getId(), OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode());
//            }
        }
        return "success";
    }

    /**
     * 根据签署方名字获取信息
     *
     * @param tenantName
     * @return
     */
    private ShopQiyuesuoInfoDTO getByName(String tenantName) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("tenant_name", tenantName);
        return selectOne(wrapper);
    }

    //创建合同草稿
    public String createContractDraft(Long orderId, String param, byte[] bytes, Long buyId, Long sellId, String affix) throws Exception {
        SdkClient client = new SdkClient(serverUrl, accessKey, accessSecret);
        /**
         * 根据业务分类配置进行合同发起，文件、签署流程、签署公章、签署位置均在业务分类中维护
         * 该场景模拟一个人事合同的场景，即平台方公司与员工签署合同，平台方公司先签署，员工后签
         */
        SdkResponse<Contract> draft = null;
        try {
            draft = this.draft(client, orderId, param, bytes, buyId, sellId, affix);
        } catch (Exception e) {
            log.error("创建合同草稿失败，{}", e.getMessage());
        }
        log.info("创建合同草稿成功，合同ID：{}", draft.getResult().getId());
        return draft.getResult().getId() + "";
    }

    /**
     * 创建合同草稿
     *
     * @param client
     * @return
     * @throws Exception
     */
    private SdkResponse<Contract> draft(SdkClient client, Long orderId, String param, byte[] bytes, Long buyId, Long sellId, String affix) throws Exception {
        log.info("contract-----orderId="+orderId+"-----start");
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();//契约锁日志
        ShopQiyuesuoInfoDTO buyerShopQIyuesuoDTO = getByShopId(buyId);//买方信息
        ShopQiyuesuoInfoDTO sellerShopQIyuesuoDTO = getByShopId(sellId);//卖方信息
        Contract draftContract = new Contract();
        draftContract.setSubject("订单合同");
        OrderContractParamRelationDTO orderContractParamRelationDTO = orderContractParamRelationService.getByOrderId(orderId);
        draftContract.setSn(orderContractParamRelationDTO.getContractNo());//设置合同编号

        Category category = new Category();
        category.setId(Long.parseLong(orderBusinessId));
        draftContract.setCategory(category);//设置业务分类
        draftContract.setExpireTime(DateUtils.dateToStr(DateUtils.addYear(DateUtils.getCurrentDate(), 1)));//设置过期时间
        // TODO 创建合同草稿的创建人
        User user = new User();
        user.setContact(createUser);
        user.setContactType("MOBILE");
        draftContract.setCreator(user);

        // 甲方公司签署方
        Signatory companySignatory = new Signatory();//签署人
        companySignatory.setTenantName(buyerShopQIyuesuoDTO.getTenantName());
        companySignatory.setTenantType(buyerShopQIyuesuoDTO.getTenantType());
        companySignatory.setReceiver(new User(buyerShopQIyuesuoDTO.getContact(), buyerShopQIyuesuoDTO.getContactType()));//接收人
        companySignatory.setSerialNo(1);//执行顺序

        List<Action> jiaActionList = new ArrayList<>();
        Action jiaAction = new Action();//签署动作
        jiaAction.setType(buyerShopQIyuesuoDTO.getTenantType());//企业签章
//        List<User> userList = new ArrayList<>();
//        userList.add(new User("17740209502", "MOBILE"));
//        action.setSealId(2708174916410151372L);//设置印章id
//        action.setName("乙企业签章-手动");//设置企业签章名字
//        action.setOperators(userList);//设置公章签署人或审批人
        jiaActionList.add(jiaAction);
        companySignatory.setActions(jiaActionList);//设置签署动作

        draftContract.addSignatory(companySignatory);

        // 乙方公司签署方
        Signatory companySignatory2 = new Signatory();
        companySignatory2.setTenantName(sellerShopQIyuesuoDTO.getTenantName());
        companySignatory2.setTenantType(sellerShopQIyuesuoDTO.getTenantType());
        companySignatory2.setReceiver(new User(sellerShopQIyuesuoDTO.getContact(), sellerShopQIyuesuoDTO.getContactType()));
        companySignatory2.setSerialNo(2);

        List<Action> yiActionList = new ArrayList<>();
        Action yiAction = new Action();//签署动作
        yiAction.setType(sellerShopQIyuesuoDTO.getTenantType());//企业签章
        //List<User> jiauserList = new ArrayList<>();
        //jiauserList.add(new User("13092867981", "MOBILE"));
        //jiaaction.setSealId(2707890404224668496L);//设置印章id
        //jiaaction.setName("甲企业签章-手动");//设置企业签章名字
        //jiaaction.setOperators(jiauserList);//设置公章签署人或审批人
        yiActionList.add(yiAction);
        companySignatory2.setActions(yiActionList);//设置签署动作

        draftContract.addSignatory(companySignatory2);
        draftContract.setSend(false); // 创建合同草稿不发起合同

        ContractDraftRequest contractDraftRequest = new ContractDraftRequest(draftContract);
        shopQiyuesuoInfoLogSaveBO.setRequetsParam(JSON.toJSONString(contractDraftRequest));
        shopQiyuesuoInfoLogSaveBO.setType(2);
        shopQiyuesuoInfoLogSaveBO.setInfoType(0);
        shopQiyuesuoInfoLogSaveBO.setStep(1);
        String response = null;
        try {
            response = client.service(contractDraftRequest);
        } catch (Exception e) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam("创建合同草稿请求服务器失败，失败原因：" + e.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            throw new Exception("创建合同草稿请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<Contract> sdkResponse = JSONUtils.toQysResponse(response, Contract.class);
        if (!sdkResponse.getCode().equals(0)) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam("创建合同草稿失败，失败原因：" + sdkResponse.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            throw new Exception("创建合同草稿失败，失败原因：" + sdkResponse.getMessage());
        }
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(sdkResponse));
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
        this.addOrderContractAttachment(sdkResponse.getResult(), orderId, affix);
        this.addContractDocumentFile(sdkResponse.getResult(), orderId, param, bytes, buyerShopQIyuesuoDTO, sellerShopQIyuesuoDTO);
        log.info("contract-----buyId="+buyId+"-----end");
        return sdkResponse;
    }

    /**
     * @return : void
     * @Author :chenyu.wang
     * @Description : 添加订单合同附件
     * @Date : 15:38 2021.01.08
     * @Param : [contract, orderId, annex]
     **/
    private void addOrderContractAttachment(Contract contract, Long orderId, String annex) {
        if (CustomizeUtil.strIsNull(annex)) {
            return;
        }
        log.info("添加订单合同文档开始");
        // 合同id
        Long contractId = contract.getId();
        log.info("合同id:{}", contractId);
        String[] fileArray = annex.split(",");
        int sort = 1;
        for (String s : fileArray) {
            try {
                sort += 1;
                // 从本地下载文件
                byte[] downloadFile = fileService.downloadFile(s);
                // 添加合同文档
                Long documentId = this.addContractDocument(downloadFile, contractId, sort);
                // 添加本地数据库
                OrderContractEnclosureDTO enclosureDTO = new OrderContractEnclosureDTO();
                enclosureDTO.setOrderId(orderId);
                enclosureDTO.setCaontractId(contractId);
                enclosureDTO.setFileUrl(s);
                enclosureDTO.setDocumentId(documentId);
                enclosureDTO.setId(ymlConfig.getPkId());
                orderContractEnclosureService.insert(enclosureDTO);
            } catch (Exception e) {
                log.info("添加订单合同文档失败");
                throw new RuntimeException("添加订单合同文档失败");
            }
        }
    }

    /**
     * 添加合同文档
     *
     * @param contract
     */
    private void addContractDocumentFile(Contract contract, Long orderId, String param, byte[] bytes, ShopQiyuesuoInfoDTO buyerShopQIyuesuoDTO,
                                         ShopQiyuesuoInfoDTO sellerShopQIyuesuoDTO) throws IOException {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();//契约锁日志
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        if (null != bytes) {
            // 添加合同文档
            String str = new String(bytes);
            log.info(str);
            DocumentAddByFileRequest request = new DocumentAddByFileRequest(contract.getId(), new StreamFile(new ByteArrayInputStream(bytes)),
                    "html", "合同模板一");
            request.setDocumentSort(1);
            shopQiyuesuoInfoLogSaveBO.setType(2);
            shopQiyuesuoInfoLogSaveBO.setRequetsParam(JSON.toJSONString(request));
            shopQiyuesuoInfoLogSaveBO.setInfoType(0);
            shopQiyuesuoInfoLogSaveBO.setStep(2);
            String response = null;
            try {
                response = sdkClient.service(request);
            } catch (ServiceException e) {
                shopQiyuesuoInfoLogSaveBO.setStatus(1);
                shopQiyuesuoInfoLogSaveBO.setResponseParam("添加文档失败，错误原因{}" + e.getMessage());
                shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
                throw new RuntimeException("添加文档失败，错误原因{}" + e.getMessage());
            }
            SdkResponse<DocumentAddResult> responseObj = JSONUtils.toQysResponse(response, DocumentAddResult.class);
            if (responseObj.getCode() == 0) {
                DocumentAddResult result = responseObj.getResult();
                shopQiyuesuoInfoLogSaveBO.setStatus(0);
                shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(responseObj));
                shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
                log.info("添加合同文档成功，文档ID:{}", result.getDocumentId());
            } else {
                shopQiyuesuoInfoLogSaveBO.setStatus(1);
                shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(responseObj));
                shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
                log.info("添加合同文档请求失败，错误码:{}，错误信息:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
            }
            initiatorContract(contract, responseObj.getResult().getDocumentId(), buyerShopQIyuesuoDTO, sellerShopQIyuesuoDTO);
        }
    }

    /**
     * 发起合同
     *
     * @param contract
     * @param documentId
     */
    private void initiatorContract(Contract contract, Long documentId, ShopQiyuesuoInfoDTO buyerShopQIyuesuoDTO,
                                   ShopQiyuesuoInfoDTO sellerShopQIyuesuoDTO) {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();//契约锁日志
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 发起时可以设置签署位置
        // 甲方
        Stamper stamper = new Stamper();
        stamper.setActionId(contract.getSignatories().get(0).getActions().get(0).getId());
        stamper.setDocumentId(documentId);
        stamper.setType(buyerShopQIyuesuoDTO.getTenantStamperType());
        stamper.setKeyword("甲方");//关键字盖章
        stamper.setKeywordIndex(-1);
        stamper.setOffsetX(0.1);
        stamper.setOffsetY(-0.1);
        // 乙方
        Stamper stamper2 = new Stamper();
        stamper2.setActionId(contract.getSignatories().get(1).getActions().get(0).getId());
        stamper2.setDocumentId(documentId);
        stamper2.setType(sellerShopQIyuesuoDTO.getTenantStamperType());
        stamper2.setKeyword("乙方");//关键字盖章
        stamper2.setKeywordIndex(-1);
        stamper2.setOffsetX(0.1);
        stamper2.setOffsetY(-0.1);
        // 时间
        Stamper stamperTime2 = new Stamper();
        stamperTime2.setActionId(contract.getSignatories().get(1).getActions().get(0).getId());
        stamperTime2.setDocumentId(documentId);
        stamperTime2.setType("TIMESTAMP");
        stamperTime2.setKeyword("签订日期");//关键字时间加盖
        stamperTime2.setKeywordIndex(1);
        stamperTime2.setOffsetX(0.02);
        stamperTime2.setOffsetY(-0.01);
        // 甲方骑缝章
        Stamper partyARidingSeamSeal = new Stamper();
        partyARidingSeamSeal.setActionId(contract.getSignatories().get(0).getActions().get(0).getId());
        partyARidingSeamSeal.setDocumentId(documentId);
        partyARidingSeamSeal.setType("ACROSS_PAGE");
        partyARidingSeamSeal.setOffsetY(0.5);
        // 乙方骑缝章
        Stamper partyARidingSeamSealB = new Stamper();
        partyARidingSeamSealB.setActionId(contract.getSignatories().get(1).getActions().get(0).getId());
        partyARidingSeamSealB.setDocumentId(documentId);
        partyARidingSeamSealB.setType("ACROSS_PAGE");
        partyARidingSeamSealB.setOffsetY(0.8);

        List<Stamper> stampers = new ArrayList<>();
        stampers.add(stamper);
        stampers.add(stamper2);
        stampers.add(stamperTime2);
        stampers.add(partyARidingSeamSeal);
        stampers.add(partyARidingSeamSealB);
        // 发起合同
        ContractSendRequest request = new ContractSendRequest(contract.getId(), stampers);
        shopQiyuesuoInfoLogSaveBO.setType(2);
        shopQiyuesuoInfoLogSaveBO.setInfoType(0);
        shopQiyuesuoInfoLogSaveBO.setRequetsParam(JSON.toJSONString(request));
        shopQiyuesuoInfoLogSaveBO.setStep(3);
        String response = null;
        try {
            response = sdkClient.service(request);
        } catch (ServiceException e) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam("发起合同请求失败 :" + e.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            e.printStackTrace();
            throw new RuntimeException("发起合同请求失败 :" + e.getMessage());
        }
        SdkResponse<Object> responseObj = JSONUtils.toQysResponse(response);
        if (responseObj.getCode() != 0) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam("请求失败:" + JSON.toJSONString(responseObj));
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            log.error("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
            return;
        }
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(responseObj));
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
        log.info("合同发起成功");
    }

    /**
     * 查看契约锁合同id
     *
     * @param contractId 契约锁合同id
     * @return
     */
    @Override
    public String getContractString(Long contractId) {
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        ContractViewPageRequest request = new ContractViewPageRequest(contractId);
        String response = sdkClient.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            log.info("合同页面地址为:{}", result.getPageUrl());
        } else {
            log.error("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
        return responseObj.getResult().getPageUrl();
    }

    /**
     * 契约锁获取签署页面
     *
     * @param ShopId
     * @param contractId
     * @param type       1单订单 2多订单
     * @param signType   1买家签署 2卖家签署
     * @return
     */
    @Override
    public String getSignaturePage(Long ShopId, Long contractId, int type, String orderIds, int signType) {
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = getByShopId(ShopId);//签署人信息
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        ContractPageRequest request = null;
        String callBackUrl = null;
        // 合同页面
        if (signType == 2) {//卖家签署
            //合同待签订页面
            callBackUrl = pageShowUrl + "/sleStore/inquirePage?orderIds=" + orderIds;
        } else {//买家签署
            if (type == 1) {//单订单
                callBackUrl = pageShowUrl + "/home/payorder?orderIds=" + orderIds;
            } else {//多订单
                callBackUrl = pageShowUrl + "/contract?orderIds=" + orderIds;
            }
        }
        request = new ContractPageRequest(contractId,
                new User(shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType()), callBackUrl);
        String response = sdkClient.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            log.info("合同页面地址为:{}", result.getPageUrl());
        } else if (responseObj.getCode() == 1601) {
            log.error("请求失败:余额不足");
            throw new RuntimeException("请求失败:余额不足");
        } else {
            log.error("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
            throw new RuntimeException("请求失败，错误码:" + responseObj.getCode() + "，错误信息:" + responseObj.getMessage());
        }
        return responseObj.getResult().getPageUrl();
    }

    /**
     * 契约锁获取废弃合同签署页面
     *
     * @param ShopId     店铺id
     * @param contractId 合同id
     * @param signType   1买家签署 2卖家签署
     * @return
     */
    @Override
    public String getAbandonSignaturePage(Long ShopId, Long contractId, int signType) {
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = getByShopId(ShopId);//签署人信息
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        ContractPageRequest request = null;
        String callBackUrl = null;
        if (signType == 1) {//买家签署
            //合同待签订页面
            callBackUrl = pageShowUrl + "/home/personCenter/myContract?type=2";
        } else {//卖家签署
            callBackUrl = pageShowUrl + "/sleStore/sleMyContract?type=3";
        }
        request = new ContractPageRequest(contractId,
                new User(shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType()), callBackUrl);
        String response = sdkClient.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            log.info("合同页面地址为:{}", result.getPageUrl());
        } else if (responseObj.getCode() == 1601) {
            log.error("请求失败:余额不足");
            throw new RuntimeException("请求失败:余额不足");
        } else {
            log.error("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
            throw new RuntimeException("请求失败，错误码:" + responseObj.getCode() + "，错误信息:" + responseObj.getMessage());
        }
        return responseObj.getResult().getPageUrl();
    }

    @Override
    public boolean updatePhoneById(ShopQiyuesuoInfoDTO bo) {
        //发送短信
        SmsInfoSaveCaptchaBO smsInfoSaveBO = new SmsInfoSaveCaptchaBO();
        smsInfoSaveBO.setShopId(bo.getShopId());
        smsInfoSaveBO.setCaptchaType(0);
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(bo.getShopId());
        if (shopInfoDTO!=null){
            EntityWrapper<ShopQiyuesuoInfoDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id",shopInfoDTO.getId());
            ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = this.selectOne(wrapper);
            if (shopQiyuesuoInfoDTO!=null){
                smsInfoSaveBO.setMobile(shopQiyuesuoInfoDTO.getContact());
            }else {
                return false;
            }
        }else {
            return false;
        }
        try {
            smsInfoService.saveALCaptcha(smsInfoSaveBO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送短信失败!");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean CheckPhone(Long shopId,String captcha,String newCaptcha,String mobile,String newMobile) {
        log.info("captcha--------"+captcha+"--------newCaptcha------"+newCaptcha+"----------mobile---------"+mobile+"------newMobile---------"+newMobile);
        Wrapper<SmsInfoDTO> wrapper = new EntityWrapper();
        wrapper.eq("status", 0);
        wrapper.eq("mobile", mobile);
        //wrapper.ge("create_time", DateUtils.addMinute(new Date(), -5));
        wrapper.eq("captcha_type", 12);
        wrapper.eq("is_verify", 0);
        wrapper.orderBy("id", false);
        wrapper.last("limit 1");
        SmsInfoDTO dto = smsInfoService.selectOne(wrapper);

        if(dto == null){
            log.info("----------------------------1");
            //throw new RuntimeException("请求失败，未查询到旧手机验证码:");
            return false;
        }
        log.info("==========dto="+dto.toString());
        dto.setIsVerify(1);
        if(!smsInfoService.updateById(dto)){
            log.info("----------------------------2");
            return false;
        }

        Wrapper<SmsInfoDTO> wrapper1 = new EntityWrapper();
        wrapper1.eq("status", 0);
        wrapper1.eq("mobile", newMobile);
        wrapper1.eq("is_verify", 0);
        wrapper1.eq("captcha_type", 12);
        wrapper1.orderBy("id", false);
        wrapper1.last("limit 1");
        SmsInfoDTO dto1 = smsInfoService.selectOne(wrapper1);

        if(dto1 == null){
            //throw new RuntimeException("请求失败，未查询到新手机验证码:");
            return false;
        }
        log.info("==========dto1="+dto1.toString());
        dto1.setIsVerify(1);
        if(!smsInfoService.updateById(dto1)){
            //throw new RuntimeException("更新新手机验证码状态失败");
            return false;
        }

        if(!(captcha.equalsIgnoreCase(dto.getCode()) && newCaptcha.equalsIgnoreCase(dto1.getCode()))){
           // throw new RuntimeException("验证码错误");
            return false;
        }
        EntityWrapper<ShopQiyuesuoInfoDTO> qiyuesuoInfoDTOEntityWrapper = new EntityWrapper<>();
        qiyuesuoInfoDTOEntityWrapper.eq("shop_id",shopId);
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = this.selectOne(qiyuesuoInfoDTOEntityWrapper);
        if (shopQiyuesuoInfoDTO==null){
           // throw new RuntimeException("原来手机号为查询到信息");
            return false;
        }
        if (!(shopQiyuesuoInfoDTO.getContact().equals(mobile))){
           // throw new RuntimeException("和原来手机号不匹配");
            return false;
        }
        shopQiyuesuoInfoDTO.setContact(newMobile);
        return this.updateById(shopQiyuesuoInfoDTO);
    }

    /*
     * 添加合同文档
     * */
    private Long addContractDocument(byte[] fileByte, Long contractId, Integer sort) {
        // 日志记录
        ShopQiyuesuoInfoLogDTO logSaveBO = new ShopQiyuesuoInfoLogDTO();
        // 文件
        ByteArrayInputStream inputStream = new ByteArrayInputStream(fileByte);
        StreamFile streamFile = new StreamFile(inputStream);
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        DocumentAddByFileRequest documentAddByFileRequest = new DocumentAddByFileRequest(contractId, streamFile, "pdf", "附件");
        documentAddByFileRequest.setDocumentSort(sort);
        String response = sdkClient.service(documentAddByFileRequest);
        // 响应结果对象
        SdkResponse<DocumentAddResult> responseObj = JSONUtils.toQysResponse(response, DocumentAddResult.class);
        // 响应码
        Integer responseCode = responseObj.getCode();
        // 响应信息
        String responseMessage = responseObj.getMessage();
        // 响应结果
        DocumentAddResult responseResult = responseObj.getResult();
        // 保存日志
        logSaveBO.setId(ymlConfig.getPkId());
        logSaveBO.setRequetsParam(JSON.toJSONString(documentAddByFileRequest));
        logSaveBO.setType(3);
        logSaveBO.setInfoType(0);
        logSaveBO.setStep(2);
        if (responseCode != 0) {
            logSaveBO.setResponseParam(responseMessage);
            logSaveBO.setStatus(1);
            shopQiyuesuoInfoLogService.insert(logSaveBO);
            log.info("请求失败，错误码:{}，错误信息:{}", responseCode, responseMessage);
            throw new RuntimeException(responseMessage);
        }
        logSaveBO.setResponseParam(responseMessage);
        logSaveBO.setStatus(0);
        shopQiyuesuoInfoLogService.insert(logSaveBO);
        log.info("添加合同文档成功，文档ID:{}", responseResult.getDocumentId());
        return responseResult.getDocumentId();
    }

    /**
     * 查询合同详情
     *
     * @param contractId
     * @return
     */
    private Contract getContactDetail(Long contractId) {
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 合同详情
        ContractDetailRequest request = new ContractDetailRequest(contractId);

        String response = sdkClient.service(request);
        SdkResponse<Contract> responseObj = JSONUtils.toQysResponse(response, Contract.class);
        if (responseObj.getCode() != 0) {
            log.info("查询合同详情请求失败，错误码:{}，错误信息:{},contractId:{}", responseObj.getCode(), responseObj.getMessage(), contractId);
            return null;
        }
        Contract contract = responseObj.getResult();
        //log.info("合同详情查询，合同主题：{}", contract.getSubject());
        return contract;
    }

    /**
     * 返回合同签署状态
     *
     * @param contractId 合同id
     * @param type       1买家 2卖家
     * @return true签署 false未签署
     */
    @Override
    public boolean getSignContactState(Long contractId, int type) {
        Contract contactDetail = getContactDetail(contractId);
        if(contactDetail == null){
            return false;
        }
        if (type == 1) {//买家
            return contactDetail.getSignatories().get(0).getStatus().equals("SIGNED");
        }
        //卖家
        return contactDetail.getSignatories().get(1).getStatus().equals("SIGNED");
    }

    /**
     * 撤回合同
     *
     * @param contractId   合同id
     * @param contactState 合同状态
     */
    @Override
    public boolean cancelContact(Long contractId, Integer contactState) {
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        if (contactState == 2) {//卖家签订
            // “已完成”状态下请求作废合同，同时发起方签署作废合同
            ContractInvalidRequest request = new ContractInvalidRequest(contractId, null, "请求作废合同", false);
            String response = sdkClient.service(request);
            SdkResponse responseObj = JSONUtils.toQysResponse(response);
            if (responseObj.getCode() == 0) {
                log.info("合同作废请求成功");
                return true;
            } else {
                log.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
            }
            return false;
        }
        // “签署中”状态下撤回合同
        ContractInvalidRequest request = new ContractInvalidRequest(contractId, "撤回合同");
        String response = sdkClient.service(request);
        SdkResponse responseObj = JSONUtils.toQysResponse(response);
        if (responseObj.getCode() == 0) {
            log.info("合同撤回成功");
            return true;
        }
        log.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        return false;

// “草稿”状态下删除合同
//    ContractInvalidRequest request = new ContractInvalidRequest(2589382258757710050L);
//    String response = sdkClient.service(request);
//    SdkResponse responseObj = JSONUtils.toQysResponse(response);
//    if(responseObj.getCode() == 0) {
//      logger.info("合同删除请求成功");
//    } else {
//      logger.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
//    }
    }

    /**
     * 签署作废合同
     *
     * @return
     */
    public Result signAbandonContact(Long contractId) {
        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 发起方签署作废合同
        ContractSignInvalidRequest request = new ContractSignInvalidRequest(contractId);
        String response = sdkClient.service(request);
        SdkResponse responseObj = JSONUtils.toQysResponse(response, Contract.class);
        if (responseObj.getCode() == 0) {
            log.info("签署作废成功");
        } else {
            log.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
        return new Result();
    }

    /**
     * 获取企业认证链接
     *
     * @param shopQiyuesuoInfoDTO
     * @return
     */
    @Override
    public Result getEnterpriseAuthenticationStr(ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO) {
        // 契约锁日志
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        User applicant = new User(null, shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType());
        String applicantInfo = JSONUtils.toJson(applicant);
        CompanyAuthLicensePCPageRequest request = new CompanyAuthLicensePCPageRequest();
        Long shopId = shopQiyuesuoInfoDTO.getShopId();
        // 营业执照
        ShopQualificationDTO shopQualificationDTO = shopQualificationService.getByShopIdAndType(shopId, 0);
        //公司名字
        String companyName = shopQiyuesuoInfoDTO.getCompanyName();
        //获取企业认证状态
        CorpAuthInfoBO enterpriseAuthenticationState = this.getEnterpriseAuthenticationState(companyName);
        if (Objects.equals("2", enterpriseAuthenticationState.getStatus())) {
            //认证通过
            shopQiyuesuoInfoDTO.setAuthenticationStatus("2");
            //更新状态
            this.updateById(shopQiyuesuoInfoDTO);
            return new Result<>(CodeEnum.QIYUESUO_COMPANYAUTH_SAME_SUCCESS);
        }
        //公司法人
        String legalPerson = shopQiyuesuoInfoDTO.getLegalPerson();
        //信用代码
        String registerNo = shopQiyuesuoInfoDTO.getRegisterNo();
        request.setCompanyName(companyName);
        request.setApplicantInfo(applicantInfo);
        request.setLegalPerson(legalPerson);
        request.setRegisterNo(registerNo);
        request.setCallbackUrl(pageInterfaceUrl + "/shopping-client/api/shopQiyuesuoInfo/getCallBackAuthInfo");
        StreamFile streamFile;
        try {
            byte[] bytes = fileService.downloadFile(shopQualificationDTO.getFileUrl());
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            streamFile = new StreamFile(inputStream);
        } catch (Exception e) {
            log.info("获取企业认证链接营业执照报错信息:{}", e.getMessage());
            e.printStackTrace();
            return new Result<>(CodeEnum.QIYUESUO_FAIL);
        }
        request.setLicense(streamFile);
        shopQiyuesuoInfoLogSaveBO.setRequetsParam(JSON.toJSONString(request));
        shopQiyuesuoInfoLogSaveBO.setType(1);
        shopQiyuesuoInfoLogSaveBO.setInfoType(1);
        String response;
        try {
            log.info("请求契约锁接口参数:{}", JSON.toJSONString(request));
            response = sdkClient.service(request);
        } catch (ServiceException e) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam(e.getMessage());
            //添加日志
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            e.printStackTrace();
            log.error("sdkClient.service is error", e);
            return new Result<>(CodeEnum.QIYUESUO_FAIL);
        }
        shopQiyuesuoInfoLogSaveBO.setResponseParam(response);
        SdkResponse<CompanyAuthPageResult> pageResultResponse = JSONUtils.toQysResponse(response, CompanyAuthPageResult.class);
        Integer code = pageResultResponse.getCode();
        log.info("企业认证返回code:{}", code);
        Result<?> result = new Result<>();
        if (code.equals(1605)) {//公司已经认证或者已经通过验证
            shopQiyuesuoInfoDTO.setAuthenticationStatus("2");
            updateById(shopQiyuesuoInfoDTO);//更新状态
            shopQiyuesuoInfoLogSaveBO.setStatus(0);
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);//添加日志
            return new Result<>(CodeEnum.QIYUESUO_COMPANYAUTH_SAME_SUCCESS);
        } else {
            CompanyAuthPageResult companyAuthPageResult = pageResultResponse.getResult();
            if (null == companyAuthPageResult) {
                shopQiyuesuoInfoLogSaveBO.setStatus(1);
                shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);//添加日志
                log.error("shopQiyuesuoInfoLogService.add is error:{}", JSON.toJSONString(companyAuthPageResult));
                return new Result<>(CodeEnum.QIYUESUO_FAIL);
            }
        }
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);//添加日志
        result.setMsg(pageResultResponse.getResult().getAuthUrl());
        return result;
    }

    /**
     * 企业添加员工信息
     *
     * @param user
     */
    private void addCompanyEmployee(User user) {
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 添加员工
        EmployeeCreateRequest request = new EmployeeCreateRequest(user, "");
        String response = sdkClient.service(request);
        SdkResponse<Employee> responseObj = JSONUtils.toQysResponse(response, Employee.class);
        if (responseObj.getCode() == 0) {
            Employee result = responseObj.getResult();
            log.info("创建员工，员工ID：{}", result.getId());
        } else {
            log.info("创建员工失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
    }


    /**
     * 获取企业认证状态
     *
     * @param companyName
     * @return
     */
    @Override
    public CorpAuthInfoBO getEnterpriseAuthenticationState(String companyName) {
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        CompanyAuthResultRequest request = new CompanyAuthResultRequest();
        request.setCompanyName(companyName);
        String response = sdkClient.service(request);
        SdkResponse<CompanyAuthResult> resultResponse = JSONUtils.toQysResponse(response, CompanyAuthResult.class);
        CompanyAuthResult result = resultResponse.getResult();
        if (resultResponse.getCode() == 0) {//查询成功
            CorpAuthInfoBO corpAuthInfoBO = new CorpAuthInfoBO();
            BeanUtils.copyProperties(result, corpAuthInfoBO);
            return corpAuthInfoBO;
        }
        return null;
    }


    private HttpURLConnection download(SdkRequest request, SdkClient sdkClient) throws ServiceException {
        String url = this.serverUrl + request.getUrl();
        Long timestamp = System.currentTimeMillis();
        String nonce = UUID.randomUUID().toString();
        String signature = MD5.toMD5(this.accessKey + this.accessSecret + timestamp + nonce);
        HttpHeader header = new HttpHeader(this.accessKey, timestamp, signature, "JAVA-3.1.7", nonce);

        try {
            return doDownload(url, request.getHttpParameter(), header, sdkClient.getConnectTimeout(), sdkClient.getReadTimeout());
        } catch (Exception var9) {
            throw new ServiceException(var9.getMessage(), var9);
        }
    }

    private HttpURLConnection doDownload(String url, HttpParameter params, HttpHeader header, int connectTimeout, int readTimeout) throws Exception {
        HttpURLConnection conn = null;
        String query = params.getQueryString("UTF-8");
        URL getUrl = buildGetUrl(url, query);
        int responseCode = 200;
        int i = 0;

        while (i <= 2) {
            try {
                conn = HttpConnection.getConnection(getUrl, HttpMethod.GET, header);
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
                responseCode = conn.getResponseCode();
                break;
            } catch (Exception var16) {
                HttpConnection.close(conn);
                if (i == 2) {
                    throw var16;
                }

                ++i;
            }
        }
        return conn;
    }

    private static URL buildGetUrl(String url, String query) throws IOException {
        if (StringUtils.isEmpty(query)) {
            return new URL(url);
        } else {
            StringBuilder newUrl = new StringBuilder(url);
            boolean hasQuery = url.contains("?");
            boolean hasPrepend = url.endsWith("?") || url.endsWith("&");
            if (!hasPrepend) {
                if (hasQuery) {
                    newUrl.append("&");
                } else {
                    newUrl.append("?");
                    hasQuery = true;
                }
            }

            newUrl.append(query);
            hasPrepend = false;
            return new URL(newUrl.toString());
        }
    }
}
